package com.dream.mqpushserver.netty2;

import com.alibaba.fastjson.JSON;
import com.dream.mqpushserver.common.RpcRequest;
import com.dream.mqpushserver.common.RpcResult;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;

/**
 * rpc 解码器
 */
public class RpcDeCoder extends LengthFieldBasedFrameDecoder {

    public RpcDeCoder(int maxFrameLength, int lengthFieldOffset, int lengthFieldLength) {
        super(maxFrameLength, lengthFieldOffset, lengthFieldLength);
    }

    @Override
    protected Object decode(ChannelHandlerContext ctx, ByteBuf in) throws Exception {
        in  = (ByteBuf)super.decode(ctx, in);

        if (in == null ){
            System.err.println("received data is null " + ctx.channel().remoteAddress());
            return null ;
        }

        if (in.readableBytes() <= 5){
            System.err.println("this data less than normal length ");
            return null ;
        }

        /**
         * 1 request
         * 2 response
         *
         */
        byte type = in.readByte();

        /**
         * data length
         */
        int length  = in.readInt();

        if (in.readableBytes() != length ){
            System.err.println("剩余字符长度与预期长度不符");
            return null ;
        }
        byte[] bytes = new byte[length];
        in.readBytes(bytes);
        if (type == 1){
            return JSON.parseObject(new String(bytes), RpcRequest.class);
        }else if (type == 2) {
            System.out.println("decode to RpcResult data : "+ new String(bytes));
            return JSON.parseObject(new String(bytes), RpcResult.class);
        }else {
            System.err.println("request data type is error ");
            return null ;
        }
    }
}
